package com.example.test_load_pic_rough;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.example.test_load_pic_rough.util.OpenFilesBySystemUtils;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luck.picture.lib.style.BottomNavBarStyle;
import com.luck.picture.lib.style.PictureSelectorStyle;
import com.luck.picture.lib.style.SelectMainStyle;
import com.luck.picture.lib.style.TitleBarStyle;
import com.previewlibrary.GPreviewBuilder;
import com.previewlibrary.ZoomMediaLoader;
import com.xuexiang.xui.widget.imageview.IconImageView;
import com.xuexiang.xui.widget.imageview.preview.PreviewBuilder;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import me.rosuh.filepicker.adapter.FileListAdapter;
import me.rosuh.filepicker.config.FilePickerManager;
import me.rosuh.filepicker.config.ItemClickListener;

/**
 * 使用xui的iconImageview和glide实现本地图片预览，导致图片失真，不知道是谁的缘故，
 * 1 单独使用glide加载本地图片观察是否失真
 */
public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestStoragePermission();
        initPicView();
        initClickEvent();
        initDocView();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 333) {
            Toast.makeText(MainActivity.this, "照片返回", Toast.LENGTH_SHORT).show();
        }
    }

    private void initPicView() {
        //这种方式加载较大的图片时，在小手机上显示的非常模糊，就算是放大也看不清楚
        IconImageView iconImageView = findViewById(R.id.iv);
        iconImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImagePreviewInfo imagePreviewInfo = new ImagePreviewInfo("/storage/emulated/0/a_test_file/pic.png");
                PreviewBuilder.from(MainActivity.this)
                        //.setImgs(imagePreviewInfos)
                        .setImg(imagePreviewInfo)
                        .setCurrentIndex(0)
                        .setSingleFling(true)
                        //.setProgressColor(SettingSPUtils.getInstance().isUseCustomTheme() ? R.color.custom_color_main_theme : R.color.xui_config_color_main_theme)
                        .setType(PreviewBuilder.IndicatorType.Number)
                        .start();
            }
        });

        //第二个图片加载组件 -- 这种方式可解决上述问题，
        IconImageView iv2 = findViewById(R.id.iv2);
        iv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ZoomMediaLoader.getInstance().init(new TestImageLoader());

                List<PicturePreviewInfo> stringList = new ArrayList<>();   //数据集合
                //stringList.add(new PicturePreviewInfo("/storage/emulated/0/a_test_file/video1.mp4" ,"/storage/emulated/0/a_test_file/video1.mp4"));
                stringList.add(new PicturePreviewInfo("/storage/emulated/0/a_test_file/pic.png", "/storage/emulated/0/a_test_file/pic.png"));
                //stringList.add(new PicturePreviewInfo("", "/storage/emulated/0/a_test_file/toolarge.jpg"));
                //stringList.add(new UserViewInfo("/storage/emulated/0/tkthresearch/SDK/download/Screenshot_20250210-104639-xx.png"));
                GPreviewBuilder.from(MainActivity.this)//这里放入activity，me是我自己的命名。
                        .setData(stringList)//放入数据集合
                        .setCurrentIndex(0)//放入你需要查看图片的下标（通常我们使用RecyclerView来展示图片，可以在点击item时放入此代码块，这样可以实现点击查看图片的功能，下标就是为了知道当前展示的是哪一张图）
                        .setSingleFling(true)//是否在黑屏区域点击返回
                        .setDrag(true)//是否禁用图片拖拽返回
                        .setType(GPreviewBuilder.IndicatorType.Number)//指示器类型
                        .start();//启动
            }
        });
    }

    private void initClickEvent() {
        Button filepicker = findViewById(R.id.filePicker);
        filepicker.setOnClickListener(v -> {
            pickFiles();
        });

        Button button = findViewById(R.id.phonePicker);
        button.setOnClickListener(v -> {
            Log.e("aaa", "initClickEvent: 点击图片选择");

            //lucypictureselector
            showAlbum();
            //Xui使用的方法
//            PhotoPicker.builder()
//                    .setShowCamera(true)
//                    .setShowGif(true)
//                    .start(PhotoPickerActivity.class,33);


//            Matisse
//                    .from(MainActivity.this)
//                    .choose(MimeType.allOf())//照片视频全部显示
//                    .countable(true)//有序选择图片
//                    .maxSelectable(9)//最大选择数量为9
//                    .gridExpectedSize(120)//图片显示表格的大小getResources()
//                    .getDimensionPixelSize(R.dimen.grid_expected_size)
//                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//图像选择和预览活动所需的方向。
//                    .thumbnailScale(0.85f)//缩放比例
//                    .theme(R.style.Matisse_Zhihu)//主题  暗色主题 R.style.Matisse_Dracula
//                    .imageEngine(new GlideEngine())//加载方式
//                    .forResult(REQUEST_CODE_CHOOSE);//请求码


        });

        Button jump = findViewById(R.id.jump);
        jump.setOnClickListener(v -> {
            Log.e(TAG, "initClickEvent: recyclerview的item拖拽");
            Intent intent = new Intent(MainActivity.this, TestDragActivity.class);
            startActivity(intent);

        });

        Button jumpChromometer = findViewById(R.id.jumpChromoteter);
        jumpChromometer.setOnClickListener(v -> {
            Log.e(TAG, "initClickEvent: 跳转多个计时器");
            Intent intent = new Intent(MainActivity.this , ChronometerActivity.class);
            startActivity(intent);
        });

        Button jumpCutVideo = findViewById(R.id.jumpCutVideo);
        jumpCutVideo.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this , CutVideoActivity.class);
            startActivity(intent);
        });

        Button useContentProvier = findViewById(R.id.useContentProvider);
        useContentProvier.setOnClickListener(v->useContentProviderMethod());

        Button loadToolargePic = findViewById(R.id.loadTooLargePic);
        loadToolargePic.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this , LoadTooLargePicByIconImageView.class);
            startActivity(intent);
        });
    }


    private void useContentProviderMethod(){
        ContentResolver contentResolver = getContentResolver();

        ContentValues contentValues = new ContentValues();
        contentValues.put("name","测试");
        contentValues.put("age",111);
        //uri应该是内容提供者哪里提供的 鉴权信息+path?
        Uri uri = Uri.parse("content://com.example.test_content_provider/test");
        contentResolver.insert(uri,contentValues);
//        runOnUiThread(()->{
//            Toast.makeText(MainActivity.this, "调用别的内容提供器insert方法成功" , Toast.LENGTH_SHORT).show();
//        });

    }
    private void showAlbum() {
        PictureSelectorStyle pictureSelectorStyle = new PictureSelectorStyle();
        SelectMainStyle selectMainStyle = new SelectMainStyle();
        selectMainStyle.setStatusBarColor(R.color.primaryColor); //状态栏颜色
        selectMainStyle.setNavigationBarColor(R.color.primaryColor); //导航栏颜色

        TitleBarStyle titleBarStyle = new TitleBarStyle();
        titleBarStyle.setTitleBackgroundColor(R.color.primaryColor);

        BottomNavBarStyle bottomNavBarStyle = new BottomNavBarStyle();
        bottomNavBarStyle.setBottomNarBarBackgroundColor(R.color.primaryColor);

        pictureSelectorStyle.setBottomBarStyle(bottomNavBarStyle);
        pictureSelectorStyle.setTitleBarStyle(titleBarStyle);
        pictureSelectorStyle.setSelectMainStyle(selectMainStyle);

        //参数很多，根据需要添加
        PictureSelector.create(this)
                .openGallery(SelectMimeType.ofAll()) //可以只显示图片也可以图片视频都显示
                .setImageEngine(GlideEngine.createGlideEngine())
                .isDisplayCamera(false) //是否显示拍照按钮
                .setMaxSelectNum(3) //最多选择数
                .setMinSelectNum(1)
                .setSelectorUIStyle(pictureSelectorStyle) //状态栏背景色//导航栏的颜色
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        for (LocalMedia localMedia : result) {
                            Log.e(TAG, "onResult: getRealPath" + localMedia.getRealPath()); //sd卡的路径
                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    private void pickFiles() {
        //打开文件选择器，选择的结果在 onActivityResult中得到
        FilePickerManager.from(this)
                .enableSingleChoice() // 只让单选
                //.maxSelectable(2) //如果是多选的话最多选几个
                //.filter() //自定义文件过滤器
                //.setTheme() //自定义主题 默认提供了几个style
                //.isSkipDir() //是否跳过文件夹
                //.setCustomRootPath() //设置根路径 ，默认“”
                //.setItemClickListener() //文件item的点击事件
                //item的点击事件最好用fileItemOnClickListener使用ItemClickListener 可能会造成内存溢出，需要在页面销毁的时候让
                //filepickerManager release()
                .setItemClickListener(new ItemClickListener() {
                    @Override
                    public boolean onItemClick(@NonNull FileListAdapter fileListAdapter, @NonNull View view, int i) {
                        //判断是否是单选
                        if (fileListAdapter.isSingleChoice()){
                            fileListAdapter.singleCheck(i);
                        }else {
                            fileListAdapter.multipleCheck(i);
                        }
                        return false;
                    }

                    @Override
                    public boolean onItemChildClick(@NonNull FileListAdapter fileListAdapter, @NonNull View view, int i) {
                        return false;
                    }

                    @Override
                    public boolean onItemLongClick(@NonNull FileListAdapter fileListAdapter, @NonNull View view, int i) {
                        return false;
                    }
                })
                .forResult(FilePickerManager.REQUEST_CODE);
    }

    private void initDocView() {
        Button button = findViewById(R.id.docPreView);
        button.setOnClickListener(v -> {
            //openWPSDocument("/storage/emulated/0/a_test_file/txtaa.txt");
            //openDoc("/storage/emulated/0/a_test_file/txtaa.txt");


//            openDoc2("/storage/emulated/0/a_test_file/txtaa.txt");
//              openDoc2("/storage/emulated/0/a_test_file/txtaa_notexist.txt");
//
//            openDoc2("/storage/emulated/0/a_test_file/geoserver加载postgis中的osm数据，并添加样式渲染.docx");
//             openDoc2("/storage/emulated/0/a_test_file/新建 DOC 文档.doc");
//            openDoc2("/storage/emulated/0/a_test_file/geoserver加载postgis中的osm数据，并添加样式渲染.pdf");
//            openDoc2("/storage/emulated/0/a_test_file/ppt1.pptx");
//            openDoc2("/storage/emulated/0/a_test_file/新建 PPT 演示文稿.ppt");
//
            openDoc2("/storage/emulated/0/a_test_file/罗广明工作计划.xls");
//            openDoc2("/storage/emulated/0/a_test_file/新建 XLSX 工作表.xlsx");

            //openByDefault();
            //openByKfd3();
            //open2ByMySelf();
        });
    }

    private void openDoc2(String filePath) {
        File file = new File(filePath);
        if (!file.exists()){
            Toast.makeText(this, "文件不存在或已删除！", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = null;
        String surffix = filePath.substring(filePath.lastIndexOf(".")+1,filePath.length());
        if (surffix.equals("txt")){
            intent = OpenFilesBySystemUtils.getTextFileIntent(this, filePath);
        }else if (surffix.equals("doc") || surffix.equals("docx")){
             intent = OpenFilesBySystemUtils.getWordFileIntent(this, filePath);
        }else if (surffix.equals("ppt") || surffix.equals("pptx")){
            intent = OpenFilesBySystemUtils.getPPTFileIntent(this, filePath);
        }else if (surffix.equals("pdf")){
            intent = OpenFilesBySystemUtils.getPdfFileIntent(this, filePath);
        }else if (surffix.equals("xls") || surffix.equals("xlsx")){
            intent = OpenFilesBySystemUtils.getExcelFileIntent(this, filePath);
        }
        try {
            if (intent != null){
                startActivity(intent);
            }else {
                Log.e(TAG, "openDoc2: intent为null");
            }
        } catch (Exception e) {
            Toast.makeText(this, "未找到相关应用无法打开文件", Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 方法可以使用
     * 使用wps打开文件，如果 wps不存在跳转到浏览器下载 wps，
     * 如果连浏览器都不存在会给出提示无法下载
     * @param filePath
     */
    private void openDoc(String filePath) {
        //获取文件的类型
        String filetype = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length());
        if ("jpg".equals(filetype) || "jpeg".equals(filetype) || "bmp".equals(filetype) || "gif".equals(filetype) || "png".equals(filetype)) {
            Toast.makeText(MainActivity.this, "文件类型错误", Toast.LENGTH_LONG).show();
        } else {
            //检测是否安装了wps软件，没有安装则去下载
            if (isAvilible(MainActivity.this, "cn.wps.moffice_eng")) {
                //先查看本地是否存在此文件。存在就立即访问。否则再去下载
                // 获得存储卡的路径
                //String sdpath = Environment.getExternalStorageDirectory() + "/";
                //String sdcard2 = sdpath + "download/"+DownLoadUtil.urldecodeUTF8(filename).substring(DownLoadUtil.urldecodeUTF8(filename).lastIndexOf("/")+1);
                File file = new File(filePath);
                // 判断文件目录是否存在
                if (file.exists()) {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putString("OpenMode", "ReadOnly");// 只读模式
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setAction(android.content.Intent.ACTION_VIEW);
                    intent.setClassName("cn.wps.moffice_eng", "cn.wps.moffice.documentmanager.PreStartActivity2");

                    //Uri uri = Uri.fromFile(new File(filePath));
                    //安卓7.0之后不能使用上面的方法直接把问阿金生成一个uri，需要通过FileProvider把文件生成一个uri
                    Uri uri = FileProvider.getUriForFile(this, this.getPackageName() + ".fileprovider", file);
                    Log.e("wps访问的uri", uri + "");
                    intent.setData(uri);
                    intent.putExtras(bundle);
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(MainActivity.this, "文件不存在", Toast.LENGTH_SHORT).show();
                    //返回真实路径
//                    mSavePath = d.downloadFile(filename);
//                    if(mSavePath!=""){
//                        Intent intent = new Intent();
//                        Bundle bundle = new Bundle();
//                        bundle.putString("OpenMode", "ReadOnly");// 只读模式
//                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        intent.setAction(android.content.Intent.ACTION_VIEW);
//                        intent.setClassName("cn.wps.moffice_eng",
//                                "cn.wps.moffice.documentmanager.PreStartActivity2");
//                        Uri uri = Uri.fromFile(new File(mSavePath+DownLoadUtil.urldecodeUTF8(filename.substring(filename.lastIndexOf("/")+1,filename.length()))));
//                        Log.e("wps访问的uri", uri+"");
//                        intent.setData(uri);
//                        intent.putExtras(bundle);
//                        try {
//                            startActivity(intent);
//                        } catch (ActivityNotFoundException e) {
//                            e.printStackTrace();
//                        }
//                    }else{
//                        mDownloadDialog.show();
//                        Toast.makeText(PreceptInfoActivity.this, "下载中", Toast.LENGTH_SHORT).show();
//                    }
                }
            } else {
                Toast.makeText(MainActivity.this, "即将安装WPS", Toast.LENGTH_SHORT).show();
                try {
                    // 从市场上下载wps
                    Uri uri = Uri.parse("https://www.wps.cn");
                    // 直接从指定网址下载
                    Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(it);
                } catch (Exception e) {
                    Log.e(TAG, "openDoc: 下载wps异常");
                    Toast.makeText(MainActivity.this, "未找到浏览器以下载WPS", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }


    //检查是否安装了某个软件
    private boolean isAvilible(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pinfo.size(); i++) {
            if (pinfo.get(i).packageName.equalsIgnoreCase(packageName))
                return true;
        }
        return false;
    }


    private void requestStoragePermission() {
        //请求权限
        String[] permissionsStorage = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

        String[] permission = new String[]{Manifest.permission.MANAGE_EXTERNAL_STORAGE};

        String[] mediaPermission = new String[]{Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO};

        XXPermissions.with(MainActivity.this).permission(permission).request(new OnPermissionCallback() {
            @Override
            public void onGranted(List<String> permissions, boolean allGranted) {

            }

            @Override
            public void onDenied(List<String> permissions, boolean doNotAskAgain) {
                OnPermissionCallback.super.onDenied(permissions, doNotAskAgain);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FilePickerManager.release(); //防止文件选择器内存溢出
    }
}